package com.yuexun.beilunpatient.ui.contractmanage.ui.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yuexun.beilunpatient.R;
import com.yuexun.beilunpatient.config.AppConfig;
import com.yuexun.beilunpatient.ui.contractmanage.adapter.VideoAdapter;
import com.yuexun.beilunpatient.ui.contractmanage.bean.VideoBean;
import com.yuexun.beilunpatient.ui.contractmanage.bean.VideoListBean;
import com.yuexun.beilunpatient.ui.contractmanage.model.impl.ContractManageModel;
import com.yuexun.beilunpatient.ui.contractmanage.presenter.impl.VideoPresenter;
import com.yuexun.beilunpatient.ui.contractmanage.ui.Act_Video_Main;
import com.yuexun.beilunpatient.ui.contractmanage.ui.view.IVideoView;
import com.yuexun.beilunpatient.utils.AgeUtil;
import com.yuexun.beilunpatient.utils.ScreenUtil;
import com.yuexun.beilunpatient.widget.EmptyLayout;
import com.yuexun.beilunpatient.widget.PullToRefresh.FooterLoadingLayout;
import com.yuexun.beilunpatient.widget.PullToRefresh.PullToRefreshBase;
import com.yuexun.beilunpatient.widget.PullToRefresh.PullToRefreshList;
import com.yuexun.library.AbstractWheel;
import com.yuexun.library.OnWheelChangedListener;
import com.yuexun.library.adapters.ArrayWheelAdapter;

import org.kymjs.kjframe.ui.KJFragment;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2019/4/1 0001.
 */

public class Frag_Video extends KJFragment implements IVideoView {

    @Bind(R.id.content_list)
    PullToRefreshList contentList;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;
    @Bind(R.id.select_tv)
    TextView selectTv;
    @Bind(R.id.select_ll)
    RelativeLayout selectLl;

    private VideoAdapter adapter;
    VideoPresenter presenter;
    private int nowpage = 1;
    private int pagesize = 20;
    List<VideoListBean.DatasBean.DataBean.DataListBean> datas = new ArrayList<>();

    String[] years = new String[]{};
    int agePosition = 0;
    String startDate = "", endDate = "";

    //判断是否正在显示
    protected boolean isVisible;

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        View view = inflater.inflate(R.layout.frag_list, null);
        ButterKnife.bind(this, view);
        isVisible = true;
        return view;
    }

    @Override
    protected void initData() {
        selectLl.setVisibility(View.VISIBLE);
        presenter = new VideoPresenter(this, new ContractManageModel());

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.YEAR, - 2);
        Date d = c.getTime();
        startDate = df.format(d);
        ApiGetData(startDate, df.format(new Date()));

        listViewPreference();
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        years = AgeUtil.getAge(year, "最近两");
    }

    /**
     * 请请求数据-云影像列表
     */
    private void ApiGetData(String startDate, String endDate) {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuidPatient", PreferenceHelper.readString(getActivity(), AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("PageIndex", nowpage + "");
        params.put("PageSize", pagesize + "");
        params.put("observationDateStart", startDate);
        params.put("observationDateEnd", endDate);
        presenter.cIcheckList(params);
    }


    /**
     * 初始化ListView样式
     */
    private void listViewPreference() {
        ListView mList = contentList.getRefreshView();
        mList.setDivider(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
        mList.setOverscrollFooter(null);
        mList.setOverscrollHeader(null);
        mList.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
        contentList.setPullRefreshEnabled(true);
        contentList.setPullLoadEnabled(true);
        ((FooterLoadingLayout) contentList.getFooterLoadingLayout()).setNoMoreDataText("已经是最新状态");


        adapter = new VideoAdapter(mList, datas, R.layout.item_inspectlist);
        mList.setAdapter(adapter);

        mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Intent intent = new Intent(getActivity(), Act_Video_Main.class);
                intent.putExtra("uid", datas.get(position).getObservationUID());
                intent.putExtra("title", datas.get(position).getProcedureName()+datas.get(position).getServiceSectID());
                intent.putExtra("visitno", datas.get(position).getInPatientNO());
                intent.putExtra("time", datas.get(position).getObservationDate());
                startActivity(intent);

            }
        });

        contentList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                nowpage = 1;
                ApiGetData(startDate, endDate);
            }

            @Override
            public void onPullUpToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                nowpage = nowpage + 1;
                ApiGetData(startDate, endDate);
            }
        });

        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                nowpage = 1;
                ApiGetData(startDate, endDate);
            }
        });
    }

    private void ageDialog() {
        final Dialog dialog = new Dialog(getActivity(), R.style.dialog4style);
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.picker_content, null);
        view.findViewById(R.id.picker_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        view.findViewById(R.id.picker_done).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initSearch();
                dialog.dismiss();
            }
        });

        final AbstractWheel zone = (AbstractWheel) view.findViewById(R.id.wheel);
        zone.setVisibleItems(3);
//        zone.setCyclic(true);
        ArrayWheelAdapter<String> adapter =
                new ArrayWheelAdapter<String>(getActivity(), years);
        adapter.setTextSize(18);
        zone.setViewAdapter(adapter);
        zone.setCurrentItem(agePosition);
        zone.addChangingListener(new OnWheelChangedListener() {
            @Override
            public void onChanged(AbstractWheel wheel, int oldValue, int newValue) {
                agePosition = newValue;
            }
        });

        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.width = ScreenUtil.getScreenWidth(getActivity());
        params.gravity = Gravity.BOTTOM;
        dialog.getWindow().setAttributes(params);
        dialog.getWindow().setWindowAnimations(R.style.dialog_anim_style);
        dialog.show();
    }

    private void initSearch() {
        selectTv.setText(years[agePosition] + "年");
        if (agePosition == 0) {
            startDate = "";
            endDate = "";
        } else {
            startDate = years[agePosition] + "-01-01 00:00:00";
            endDate = years[agePosition] + "-12-31 23:59:59";
        }
        nowpage = 1;
        ApiGetData(startDate, endDate);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        isVisible = false;
    }

    @OnClick(R.id.select_ll)
    public void onViewClicked() {
        ageDialog();
    }

    @Override
    public void cIcheckList(VideoListBean videoListBean) {
        if(isVisible){
            if (contentList.isPullRefreshEnabled()) {
                contentList.onPullDownRefreshComplete();
            }
            if (videoListBean.getStatus().equals("200")) {
                if (videoListBean.getDatas().get(0).getData() != null) {
                    if (videoListBean.getDatas().get(0).getData().getDataList().size() == 0) {
                        contentList.setHasMoreData(false);
                    } else {
                        if (contentList.isPullLoadEnabled()) {
                            contentList.onPullUpRefreshComplete();
                        }
                    }

                    if (nowpage == 1) {
                        datas.clear();
                        datas = videoListBean.getDatas().get(0).getData().getDataList();
                    } else {
                        datas.addAll(videoListBean.getDatas().get(0).getData().getDataList());
                    }
                    adapter.refresh(datas);
                } else {
                    ViewInject.toast(videoListBean.getDatas().get(0).getMsg());
                }
            } else {
                ViewInject.toast(videoListBean.getMessage());
            }

            if (datas.size() == 0) {
                emptyLayout.setErrorType(EmptyLayout.NODATA);
            } else {
                emptyLayout.dismiss();
            }
        }

    }

    @Override
    public void cIcheckInfo(VideoBean videoBean) {

    }

    @Override
    public void dismiss() {

    }
}
